package com.yige.web.controller

import com.mongodb.BasicDBObject
import com.mongodb.DBObject
import com.yige.common.DateUtil
import com.yige.common.ResultUtil
import com.yige.common.SystemConstant
import com.yige.service.mongoService.MongoActionIncomeService
import com.yige.service.mongoService.MongoGoodsClassService
import com.yige.service.mongoService.MongoGoodsService
import com.yige.service.mongoService.MongoIncomeService
import com.yige.service.mongoService.MongoLessonStuService
import com.yige.service.mongoService.MongoManagerService
import com.yige.service.mongoService.MongoStudentService
import com.yige.service.mongoService.MongoTeacherService
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.stereotype.Controller
import org.springframework.ui.Model
import org.springframework.util.StringUtils
import org.springframework.web.bind.annotation.RequestMapping
import org.springframework.web.bind.annotation.RequestParam
import org.springframework.web.bind.annotation.ResponseBody

/**
 * Created by sunhao on 2015/11/2 0002.
 */

@Controller
@RequestMapping("income")
class IncomeController {

    @Autowired
    MongoIncomeService incomeService
    @Autowired
    MongoStudentService studentService
    @Autowired
    MongoTeacherService teacherService
    @Autowired
    MongoGoodsService goodsService
    @Autowired
    MongoGoodsClassService goodsClassService
    @Autowired
    MongoActionIncomeService actionIncomeService
    @Autowired
    MongoLessonStuService lessonService
    @Autowired
    MongoManagerService managerService




    /*****************控制器模块*****************/

    /**
     * 收入管理列表
     * @param model
     * @return
     */
    @RequestMapping("list.do")
    def list(Model model){
        studentArgs(model)
        teacherArgs(model)
        actionIncomeArgs(model)
        goodsArgs(model)
        goodsClassArgs(model)
        lessonArgs(model)
        managerArgs(model)
        List incomeList = incomeService.findListDescendingByDate() as LinkedList
        incomeArgs(model,incomeList)
        incomeCount(incomeList,model)
        return "income/list"
    }

    @RequestMapping("find")
    def find(Model model,String student, String teacher, String goodsClass, String startDate, String endDate,Integer status, String action){
        def query = new BasicDBObject()
        if(!StringUtils.isEmpty(student)){
            query.append("student",student)
        }
        if(!StringUtils.isEmpty(teacher)){
            query.append("teacher",teacher)
        }
        if(!StringUtils.isEmpty(goodsClass)){
            query.append("goodsClass",goodsClass)
        }
        if(!StringUtils.isEmpty(startDate) && !StringUtils.isEmpty(endDate)){
            query.append("date",[$gte:DateUtil.parseDate(startDate), $lte:DateUtil.parseDate(endDate)]as BasicDBObject)
        }
        if(status != null){
            query.append("status",status)
        }
        if(!StringUtils.isEmpty(action)){
            query.append("action",action)
        }
        studentArgs(model)
        teacherArgs(model)
        actionIncomeArgs(model)
        goodsArgs(model)
        goodsClassArgs(model)
        lessonArgs(model)
        managerArgs(model)
        def incomeList = incomeService.findListByQuery(query) as LinkedList
        incomeArgs(model,incomeList)
        incomeCount(incomeList,model)
        return "income/list"
    }

    /**
     * 添加收入
     * @param date
     * @param num
     * @param student
     * @param action
     * @param price
     * @param n
     * @param total
     * @param lesson
     * @param teacher
     * @param goodsClass
     * @param goods
     * @return
     */
    @RequestMapping("addIncome")
    @ResponseBody
    def addIncome(String date, int num, String student, String action, Double price, int n, Double total,
                  String lesson, String teacher, String goodsClass, String goods, String manager,Integer status){
        def incomeInfo = [_id:UUID.randomUUID().toString(),date:DateUtil.parseDate(date),num:num,student:student,teacher:teacher,
                          action:action,price:price,n:n,total:total,lesson:lesson,goodsClass:goodsClass,status:status,manager:manager]as BasicDBObject
        boolean flag = false
        def ns = 0
        def list = new LinkedList(),listInfo = new LinkedList()
        flag = incomeService.insertOne(incomeInfo)
        def student_db = studentService.findOneById(student),action_db = actionIncomeService.findOneById(action)
        if(student_db != null){
            student_db.payInfo.each{info->
                listInfo.add(info)
            }
            listInfo.add([id:incomeInfo._id,date:date,num:num, action:action_db.name,pay:total])
            studentService.updatePayInfoForStudent(student,listInfo)
            if(action.equals(SystemConstant.INCOME_BOOKS) || action.equals(SystemConstant.INCOME_INSTRUMENT)){
                String info = ""
                goodsClassService.reduceCountForGoods(goodsClass,n as int)
                goodsService.deliveryGoods(goods,price,date,info)
            }
            if(status == SystemConstant.INCOME_PAY){
                if(action.equals(SystemConstant.INCOME_KEFEI)){
                    student_db.lessons.each{
                        if(lesson.equals(it.id)){
                            ns = it.n + n as int
                            it = [id:it.id,name:it.name,price:it.price,n:ns]as BasicDBObject
                        }
                        list.add(it)
                    }
                    flag = studentService.updateLessonForStudent(student, list)
                }
            }
        }
        return ResultUtil.recallAjax(flag)
    }

    /**
     * 作废收入记录
     * @param _ids
     * @return
     */
    @RequestMapping("cancelIncome")
    @ResponseBody
    def cancelIncome(@RequestParam("_ids") List<String> _ids){
        boolean flag = false
        _ids.each {_id->
            flag = incomeService.changeStatus(_id,SystemConstant.INCOME_CANCEL)

        }
        return ResultUtil.recallAjax(flag)
    }


    @RequestMapping("updateIncome")
    @ResponseBody
    def updateIncome(String _id,String date, int num, String student, String action, Double price, Integer n, Double total,
                     String lesson, String teacher, String goodsClass, String goods, String manager,Integer status){
        def incomeInfo = [_id:_id,date:DateUtil.parseDate(date),num:num,student:student,teacher:teacher,
                          action:action,price:price,n:n,total:total,lesson:lesson,goods:goods,status:status,manager:manager]as BasicDBObject
        boolean flag = false
        flag = incomeService.updateOne(_id,incomeInfo)
        return ResultUtil.recallAjax(flag)
    }


    @RequestMapping("changeToPay")
    @ResponseBody
    def changeToPay(String _id){
        int status = 1
        boolean flag = false
        flag = incomeService.changeStatus(_id,status)
        return ResultUtil.recallAjax(flag)
    }



    /*****************方法模块*****************/

    def incomeArgs(Model model, List<DBObject> incomeList){
        DBObject student,action
        List<Map<String, Object>> costMaps = new ArrayList<>()
        Map<String,Object> costMap = new HashMap<>()
        incomeList.each {
            student = studentService.findOneById(it.student)
            if(student == null){
                student = [name: it.student]as BasicDBObject
            }
            action = actionIncomeService.findOneById(it.action)
            costMap.put("_id",it._id)
            costMap.put("num",it.num)
            costMap.put("date",DateUtil.formatDate(it.get("date")))
            costMap.put("student",student.name)
            costMap.put("action",action.name)
            costMap.put("pay",it.total)
            costMap.put("status",it.status)
            costMaps.add(costMap)
            costMap = new HashMap<>()
        }
        model.addAttribute("incomes",costMaps)
    }

    def incomeCount(List<DBObject> incomeList, Model model){
        def count = 0
        incomeList.each {
                count = count + it.total
        }
        model.addAttribute("incomeCount",count)
    }


    def managerArgs(Model model){
        def managerList = managerService.findList() as ArrayList
        model.addAttribute("managers",managerList)
    }

    def studentArgs(Model model){
        def studentList = studentService.findList() as ArrayList
        model.addAttribute("students",studentList)
    }

    def teacherArgs(Model model){
        def teacherList = teacherService.findList() as ArrayList
        model.addAttribute("teachers",teacherList)
    }

    def actionIncomeArgs(Model model){
        def actionList = actionIncomeService.findList() as ArrayList
        model.addAttribute("actions",actionList)
    }

    def goodsArgs(Model model){
        def goodsList = goodsService.notSoldGoods()
        model.addAttribute("goods",goodsList)
    }

    def goodsClassArgs(Model model){
        def goodsClassList = goodsClassService.findList() as ArrayList
        model.addAttribute("goodsClass",goodsClassList)
    }

    def lessonArgs(Model model){
        def lessonList = lessonService.findList() as ArrayList
        model.addAttribute("lessons",lessonList)
    }

}
